package com.zdw.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdw.common.exception.GlobalException;
import com.zdw.demo.config.international.InternationalUtils;
import com.zdw.demo.dto.SeataDemoOneDto;
import com.zdw.demo.entity.SeataDemoOneEntity;
import com.zdw.demo.feign.SeataDemoOneFeignClient;
import com.zdw.demo.mapper.SeataDemoOneMapper;
import com.zdw.demo.service.SeataDemoOneService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 卓德文
 * @since 2022-11-22
 */
@Service
public class SeataDemoOneServiceImpl extends ServiceImpl<SeataDemoOneMapper, SeataDemoOneEntity> implements SeataDemoOneService {

    @Resource
    private SeataDemoOneFeignClient seataDemoOneFeignClient;

    /**
     * 测试seata分布式事务
     *
     * @param seataDemoOneDto
     * @return
     */
    @Override
    @GlobalTransactional(name = "seataTest", rollbackFor = Exception.class)
    public int insert(SeataDemoOneDto seataDemoOneDto) {
        ResponseEntity<Integer> responseEntity = null;
        System.out.println("xid:" + RootContext.getXID());
        //1.调用当前服务方法A
        SeataDemoOneEntity seataDemoOneEntity = BeanUtil.copyProperties(seataDemoOneDto, SeataDemoOneEntity.class);
        baseMapper.insert(seataDemoOneEntity);
        //2.远程调用服务方法B(不能feign降级、不能全局拦截异常,否则全局事务失效)
        responseEntity = seataDemoOneFeignClient.testSeata(seataDemoOneEntity.getInNo(), seataDemoOneEntity.getInBound());
        //3.模拟异常,测试分布式事务回滚
        int i = 1 / 0;
        //4.结果和返回
        if (ObjectUtil.isNull(responseEntity) || ObjectUtil.isNull(responseEntity.getBody())) {
            throw new GlobalException(InternationalUtils.getInternational("common.exception"));
        }
        return responseEntity.getBody();
    }
}
